package gov.pr.celepar.sentinela.util;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Criptografia {
	private static Log logger = LogFactory.getLog(Criptografia.class);
	private static final String ALGORITIMO = "MD5";
	private static final String HEX_DIGITS = "0123456789abcdef";
	private static final String ALGORITIMO_BASE = "AES";
	private static final byte[] KEY_VALUE = new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

	public static String criptografar(String senha) {
		byte[] b = null;
		String str = senha;
		try {
			b = digest(str.getBytes(), ALGORITIMO);
		} catch (NoSuchAlgorithmException e) {
			logger.error("", e);
			return null;
		}
		return byteArrayToHexString(b);
	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			int j = b[i] & 0xFF;
			buf.append(HEX_DIGITS.charAt(j / 16));
			buf.append(HEX_DIGITS.charAt(j % 16));
		}
		return buf.toString();
	}

	private static byte[] digest(byte[] input, String palgoritmo) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(palgoritmo);
		md.reset();
		return md.digest(input);
	}

	public String generateSecurityCode() {
		return UUID.randomUUID().toString();
	}

	public static String criptografarBase(String valueToEnc) throws Exception {
		String encryptedValue = null;
		try {
		Key key = generateKey();
		Cipher c = Cipher.getInstance(ALGORITIMO_BASE);
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] encValue = c.doFinal(valueToEnc.getBytes());
		encryptedValue = new BASE64Encoder().encode(encValue);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return encryptedValue;
	}

	public static String descriptografarBase(String encryptedValue) throws Exception {
		String decryptedValue = null;
		try {
			Key key = generateKey();
			Cipher c = Cipher.getInstance(ALGORITIMO_BASE);
			c.init(Cipher.DECRYPT_MODE, key);
			byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
			byte[] decValue = c.doFinal(decordedValue);
			decryptedValue = new String(decValue);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return decryptedValue;
	}

	private static Key generateKey() throws Exception {
		Key key = new SecretKeySpec(KEY_VALUE, ALGORITIMO_BASE);
		return key;
	}

	public static void main(String[] args) throws Exception {
        String password = "teste";
        String passwordEnc = Criptografia.criptografarBase(password);
        String passwordDec = Criptografia.descriptografarBase(passwordEnc);
        System.out.println("Plain Text : " + password);
        System.out.println("Encrypted : " + passwordEnc);
        System.out.println("Decrypted : " + passwordDec);
    }
}